'''
Created on Aug 19, 2010

@author: diego
'''
import cv
from math import *
from ImageOps import grayscale

angle=0
image=0
imageRot=0
frame=0
fingerThresh=50

def on_trackbar2(val):
    global fingerThresh
    fingerThresh=val

def on_trackbar(val):
    angle=val
    mapMatrix=cv.CreateMat(2, 3, cv.CV_32F)
    cv.GetRotationMatrix2D((300,175), angle, 1, mapMatrix)            
    cv.WarpAffine(frame, imageRot, mapMatrix)
    cv.ShowImage("imageRot", imageRot)

def centroid(points):
    x=0
    y=0
    for pt in points:
        x=x+pt[0]
        y=y+pt[1]
    return(x/len(points),y/len(points))

def angle(pt1, pt2, pt0):
    "calculate angle contained by 3 points(x, y)"
    dx1 = pt1[0] - pt0[0]
    dy1 = pt1[1] - pt0[1]
    dx2 = pt2[0] - pt0[0]
    dy2 = pt2[1] - pt0[1]

    nom = dx1*dx2 + dy1*dy2
    denom = sqrt( (dx1*dx1 + dy1*dy1) * (dx2*dx2 + dy2*dy2) + 1e-10 )
    ang = nom / denom
    return ang


if __name__ == '__main__':
    fingerThresh=50
    cv.NamedWindow("angle")
    cv.CreateTrackbar("angulo", "angle", 0, 360, on_trackbar)
    cv.CreateTrackbar("fingerThresh", "angle", 1, 255, on_trackbar2)
    capture=cv.CaptureFromCAM(1)
    while(True):
        frame=cv.QueryFrame(capture)
#        rect=(20,20,600,350)
#        cv.SetImageROI(frame, rect)
        size=cv.GetSize(frame)
        
        storage=cv.CreateMemStorage(0)
#        image=cv.CloneImage(frame)
        imageRot=cv.CloneImage(frame)
        contourImage=cv.CloneImage(frame)
        
        
        #rotate image
        mapMatrix=cv.CreateMat(2, 3, cv.CV_32F)
        cv.GetRotationMatrix2D((300,175), 3, 1, mapMatrix)            
        cv.WarpAffine(frame, imageRot, mapMatrix)
        #crop to area of interest
        rect=(88,50,460,270)
        cv.SetImageROI(imageRot, rect)
        cv.ShowImage("rotated", imageRot)
        #threshold
        size=cv.GetSize(imageRot)
        grayscale=cv.CreateImage(size,8,1)
        thresh=cv.CreateImage(size, 8, 1)
        cv.CvtColor(imageRot, grayscale, cv.CV_BGR2GRAY)
        cv.Threshold(grayscale, thresh, fingerThresh, 255, cv.CV_THRESH_BINARY_INV)
        cv.EqualizeHist(grayscale, grayscale)
        
        cv.ShowImage("grayScale",grayscale)
        cv.ShowImage("threhsold", thresh)

        cv.WaitKey(10)
    